package com.edu.d6_tcp3;

import java.io.*;
import java.net.Socket;

/**
 * 创建线程子类，将socket通道交给线程进行管理，实现支持多个客户端连接服务端
 */
public class ServerReaderThread extends Thread{
    private Socket socket;
    public ServerReaderThread(Socket socket) {
        this.socket=socket;
    }

    @Override
    public void run() {
        /**
         * 3、从socket通信管道中得到一个字节输入流
         */

        try {
            InputStream inputStream = socket.getInputStream();
            /**
             * 4、用数据输入流来包装字节流
             */
            DataInputStream dataInputStream = new DataInputStream(inputStream);
            while (true) {
                try {
                    String s = dataInputStream.readUTF();
                    System.out.println(s);
                    //把这个消息分发给全部客户端进行接收
                    sendMsgToAl(s);
                } catch (Exception e) {
                    System.out.println("有人下线了"+socket.getRemoteSocketAddress());
                    Server.onLineSockets.remove(socket);
                    dataInputStream.close();
                    socket.close();
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void sendMsgToAl(String s) throws IOException {
        //发送给全部在线的socket管道进行接收
        for (Socket onLineSocket : Server.onLineSockets) {
            OutputStream os = onLineSocket.getOutputStream();
            DataOutputStream dataOutputStream = new DataOutputStream(os);
            dataOutputStream.writeUTF(s);
            dataOutputStream.flush();
        }
    }
}
